/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ui;

//import control.Factory;
import control.Manager;
import framework.dal.GroupDB;
import javax.swing.JOptionPane;
import framework.groups.Group;
import framework.groups.Groupable;
import framework.groups.Item;
import java.util.ArrayList;
import javax.swing.UnsupportedLookAndFeelException;

/**
 *
 * @author Guilherme
 */
public class MainUI extends javax.swing.JFrame implements Groupable
{

     private Group currentGroup;
     private ArrayList<NoteUI> newNotes = new ArrayList<>();
     private ArrayList<NoteUI> notesInCurrentGroup = new ArrayList<>();
     private Integer lastRow;
             
    /**
     * Creates new form MainUI
     */
    public MainUI()
    {
        initComponents();
        setLookAndFeel();
        this.setExtendedState(MAXIMIZED_BOTH);
        this.delGroup.setEnabled(false);
        this.addNote.setEnabled(false);
    }

    private  void setLookAndFeel()
    {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        try
        {
            javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
            javax.swing.SwingUtilities.updateComponentTreeUI(this);
        }
        catch(ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException erro)
        {
            javax.swing.JOptionPane.showMessageDialog(null,erro);
        }
        //</editor-fold>
    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents()
    {

        jFrame1 = new javax.swing.JFrame();
        toolBar = new javax.swing.JToolBar();
        saveAll = new javax.swing.JButton();
        jSeparator3 = new javax.swing.JToolBar.Separator();
        addNote = new javax.swing.JButton();
        jSeparator2 = new javax.swing.JToolBar.Separator();
        addGroup = new javax.swing.JButton();
        delGroup = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JToolBar.Separator();
        desktopPane = new javax.swing.JDesktopPane();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem5 = new javax.swing.JMenuItem();
        jMenu4 = new javax.swing.JMenu();
        jMenuItem3 = new javax.swing.JMenuItem();
        jMenu5 = new javax.swing.JMenu();
        jMenuItem4 = new javax.swing.JMenuItem();
        jMenu3 = new javax.swing.JMenu();
        jMenuItem6 = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        jMenuItem2 = new javax.swing.JMenuItem();
        jMenuItem1 = new javax.swing.JMenuItem();

        javax.swing.GroupLayout jFrame1Layout = new javax.swing.GroupLayout(jFrame1.getContentPane());
        jFrame1.getContentPane().setLayout(jFrame1Layout);
        jFrame1Layout.setHorizontalGroup(
            jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        jFrame1Layout.setVerticalGroup(
            jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Notes");

        toolBar.setRollover(true);

        saveAll.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ui/images/disk_multiple.png"))); // NOI18N
        saveAll.setFocusable(false);
        saveAll.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        saveAll.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        saveAll.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                saveAllActionPerformed(evt);
            }
        });
        toolBar.add(saveAll);
        toolBar.add(jSeparator3);

        addNote.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ui/images/note_add.png"))); // NOI18N
        addNote.setToolTipText("Nova anotação...");
        addNote.setFocusable(false);
        addNote.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        addNote.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        addNote.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                addNoteActionPerformed(evt);
            }
        });
        toolBar.add(addNote);
        toolBar.add(jSeparator2);

        addGroup.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ui/images/package_add.png"))); // NOI18N
        addGroup.setToolTipText("Criar grupo de anotações...");
        addGroup.setFocusable(false);
        addGroup.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        addGroup.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        addGroup.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                addGroupActionPerformed(evt);
            }
        });
        toolBar.add(addGroup);

        delGroup.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ui/images/package_delete.png"))); // NOI18N
        delGroup.setToolTipText("Remover um grupo");
        delGroup.setFocusable(false);
        delGroup.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        delGroup.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        delGroup.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                delGroupActionPerformed(evt);
            }
        });
        toolBar.add(delGroup);
        toolBar.add(jSeparator1);

        desktopPane.setBackground(new java.awt.Color(240, 240, 240));

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            Manager.nameGroupsArray(),
            new String []
            {
                "Grupo de anotações"
            }
        )
        {
            Class[] types = new Class []
            {
                java.lang.String.class
            };

            public Class getColumnClass(int columnIndex)
            {
                return types [columnIndex];
            }
        });
        jTable1.addMouseListener(new java.awt.event.MouseAdapter()
        {
            public void mouseClicked(java.awt.event.MouseEvent evt)
            {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(jTable1);

        jMenu1.setText("Backstage");

        jMenuItem5.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F4, java.awt.event.InputEvent.ALT_MASK));
        jMenuItem5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ui/images/door_out.png"))); // NOI18N
        jMenuItem5.setText("Sair");
        jMenuItem5.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                jMenuItem5ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem5);

        jMenuBar1.add(jMenu1);

        jMenu4.setText("Notas");

        jMenuItem3.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem3.setText("Criar nova anotação");
        jMenuItem3.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                jMenuItem3ActionPerformed(evt);
            }
        });
        jMenu4.add(jMenuItem3);

        jMenuBar1.add(jMenu4);

        jMenu5.setText("Grupos");

        jMenuItem4.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_G, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem4.setText("Criar novo grupo de anotações");
        jMenuItem4.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                jMenuItem4ActionPerformed(evt);
            }
        });
        jMenu5.add(jMenuItem4);

        jMenuBar1.add(jMenu5);

        jMenu3.setText("Ferramentas");

        jMenuItem6.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ui/images/cog.png"))); // NOI18N
        jMenuItem6.setText("Opções");
        jMenu3.add(jMenuItem6);

        jMenuBar1.add(jMenu3);

        jMenu2.setText("Sobre");

        jMenuItem2.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F1, 0));
        jMenuItem2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ui/images/help.png"))); // NOI18N
        jMenuItem2.setText("Ajuda");
        jMenu2.add(jMenuItem2);

        jMenuItem1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ui/images/information.png"))); // NOI18N
        jMenuItem1.setText("Sobre");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener()
        {
            public void actionPerformed(java.awt.event.ActionEvent evt)
            {
                jMenuItem1ActionPerformed(evt);
            }
        });
        jMenu2.add(jMenuItem1);

        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(toolBar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 176, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(desktopPane, javax.swing.GroupLayout.DEFAULT_SIZE, 492, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(toolBar, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(desktopPane, javax.swing.GroupLayout.DEFAULT_SIZE, 401, Short.MAX_VALUE)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void addNoteActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_addNoteActionPerformed
    {//GEN-HEADEREND:event_addNoteActionPerformed
        NoteUI u = new NoteUI();
        this.newNotes.add(u);
        this.desktopPane.add(u);
        u.setVisible(true);

    }//GEN-LAST:event_addNoteActionPerformed

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jMenuItem1ActionPerformed
    {//GEN-HEADEREND:event_jMenuItem1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jMenuItem1ActionPerformed

    private void jMenuItem5ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jMenuItem5ActionPerformed
    {//GEN-HEADEREND:event_jMenuItem5ActionPerformed
        this.dispose();
    }//GEN-LAST:event_jMenuItem5ActionPerformed

    private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jMenuItem3ActionPerformed
    {//GEN-HEADEREND:event_jMenuItem3ActionPerformed
        this.addNoteActionPerformed(evt);
    }//GEN-LAST:event_jMenuItem3ActionPerformed

    private void addGroupActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_addGroupActionPerformed
    {//GEN-HEADEREND:event_addGroupActionPerformed
        Manager.STRATEGY.createGroup();
    }//GEN-LAST:event_addGroupActionPerformed

    private void delGroupActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_delGroupActionPerformed
    {//GEN-HEADEREND:event_delGroupActionPerformed
        int row = jTable1.getSelectedRow();
        String nameGroup = null;
        if (row > -1)
        {
            nameGroup = jTable1.getValueAt(row, 0).toString();
        }
        Manager.STRATEGY.removeGroup(nameGroup);
    }//GEN-LAST:event_delGroupActionPerformed

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt)//GEN-FIRST:event_jTable1MouseClicked
    {//GEN-HEADEREND:event_jTable1MouseClicked
        this.addNote.setEnabled(true);
        this.delGroup.setEnabled(true);
        if (this.currentGroup == null || this.currentGroup.isEmpty())
        {
            int row = jTable1.getSelectedRow();
            this.lastRow = row;
            String nameGroup = jTable1.getValueAt(row, 0).toString();
            this.currentGroup = GroupDB.getGroup(nameGroup);
            if (this.currentGroup != null)
            {
                this.showNotes();
            }
        }
        else
        {
            this.saveAllActionPerformed(null);
            this.closeAll();
            this.jTable1MouseClicked(evt);
        }
    }//GEN-LAST:event_jTable1MouseClicked

    private void jMenuItem4ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jMenuItem4ActionPerformed
    {//GEN-HEADEREND:event_jMenuItem4ActionPerformed
        this.addGroupActionPerformed(evt);
    }//GEN-LAST:event_jMenuItem4ActionPerformed

    private void saveAllActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_saveAllActionPerformed
    {//GEN-HEADEREND:event_saveAllActionPerformed
        for(NoteUI n : this.notesInCurrentGroup)
        {
            n.salve();
        }
        for(NoteUI n : this.newNotes)
        {
            if (!n.salve())
            {
                return;
            }
            else
            {
                this.notesInCurrentGroup.add(n);
            }
        }
        
    }//GEN-LAST:event_saveAllActionPerformed
    
    public void closeAll()
    {
        for (NoteUI n : this.newNotes)
        {
            n.dispose();
        }
        this.newNotes.clear();
        for (NoteUI n : this.notesInCurrentGroup)
        {
            n.dispose();
        }
        this.notesInCurrentGroup.clear();
        this.currentGroup = null;
    }

    public void rePaintGroups()
    {
        this.addNote.setEnabled(false);
        this.delGroup.setEnabled(false);
        Manager.retrieveData();
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
                Manager.nameGroupsArray(),
                new String[]
        {
            "Grupo de anotações"
        })
        {
            Class[] types = new Class[]
            {
                java.lang.String.class
            };

            public Class getColumnClass(int columnIndex)
            {
                return types[columnIndex];
            }
        });
        jScrollPane2.setViewportView(jTable1);
    }
    
    public void showNotes()
    {
        for (Item i : this.currentGroup)
        {
            NoteUI n = new NoteUI(i);
            this.desktopPane.add(n);
            this.notesInCurrentGroup.add(n);
            n.setVisible(true);
        }
    }
    
    public void closeAllWithoutSave()
    {
        for (Item i : this.currentGroup)
        {
            NoteUI n = new NoteUI(i);
            this.desktopPane.add(n);
            this.notesInCurrentGroup.add(n);
            n.setVisible(true);
        }
    }
    
    public Integer getGroupSelected()
    {
        String nameGroup = jTable1.getValueAt(this.lastRow, 0).toString();
        return GroupDB.getGroupID(nameGroup);
//        int row = jTable1.getSelectedRow();
//        if (row == -1) 
//        {
//            return null;
//        }
//        else
//        {
//            String nameGroup = jTable1.getValueAt(row, 0).toString();
//            return GroupDB.getGroupID(nameGroup);
//        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addGroup;
    private javax.swing.JButton addNote;
    private javax.swing.JButton delGroup;
    private javax.swing.JDesktopPane desktopPane;
    private javax.swing.JFrame jFrame1;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenu jMenu3;
    private javax.swing.JMenu jMenu4;
    private javax.swing.JMenu jMenu5;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenuItem jMenuItem3;
    private javax.swing.JMenuItem jMenuItem4;
    private javax.swing.JMenuItem jMenuItem5;
    private javax.swing.JMenuItem jMenuItem6;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JToolBar.Separator jSeparator1;
    private javax.swing.JToolBar.Separator jSeparator2;
    private javax.swing.JToolBar.Separator jSeparator3;
    private javax.swing.JTable jTable1;
    private javax.swing.JButton saveAll;
    private javax.swing.JToolBar toolBar;
    // End of variables declaration//GEN-END:variables
}
